package wxk.study.springtx.service.impl;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import wxk.study.springtx.dal.dao.TUserMapper;
import wxk.study.springtx.dal.model.TUser;
import wxk.study.springtx.service.UserService;
import wxk.study.springtx.util.IdGenerator;

import java.util.Arrays;
import java.util.Date;

/**
 * @author wangxuekai
 * @version 2.2
 * @Date 2017/3/15.
 * @since 2.2
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    private static final Logger LOGGER = Logger.getLogger(UserServiceImpl.class);

    @Autowired
    private TUserMapper tUserMapper;

    @Transactional(propagation = Propagation.REQUIRED)
    public int addUser(TUser tUser) {
        LOGGER.info("开始增加用户");
        int result = tUserMapper.insert(tUser);
        try {
            update(tUser.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        LOGGER.info("增加用户完成,"+tUser);
        return result;
    }

    public TUser selectUser(String nickName) {
        LOGGER.info("开始数据库查询----NickName="+nickName);
        TUser user = tUserMapper.selectByNickName(nickName);
        LOGGER.info("查询到用户信息,"+user);
        return user;
    }

    public int updateUser(TUser user) {
        LOGGER.info("开始更新用户信息----"+user);
         int result = tUserMapper.updateByPrimaryKeySelective(user);
        LOGGER.info("更新记录为:"+result+",更新结果为:"+user);
        return result;
    }

    public int deleteUser(String nickName) {
        return 0;
    }


    public int batchJoinGroup(String gCode, String... nickNames) {
        try {
            return btJoin(gCode,nickNames);
        } catch (RuntimeException e) {
            LOGGER.error("出现异常啦!"+e.getMessage());
            return 0;
        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void update(Long id) {
        TUser user = tUserMapper.selectByPrimaryKey(id - 1);
        user.setMobile(IdGenerator.genMobile());
        user.setModifyTime(new Date());
        user.setBirthday(new Date());
        tUserMapper.updateByPrimaryKey(user);
        int i = 1 / 0;
    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public int btJoin(String gCode,String... nickNames){
        int result = tUserMapper.batchJoinGroup(gCode, Arrays.asList(nickNames));
        int i  = 1 / 0;
        return result;
    }
}
